import QtQuick 2.0
import QtMultimedia 5.0

Item {
    id:container
    signal btnBackClicked

    property var stage
    property bool rolling : false

    property var players_: []
    property var rollingPlayers_: []
    property int rollingIndex_ : 0
    property int groupWinnerCount_ : 0

    Text {
        id:theTitle
        text: "幸运开奖"
        font.pixelSize: 28
        font.bold: true
        color: "white"
        anchors { top: parent.top;  topMargin: 20; horizontalCenter: parent.horizontalCenter }
        height: 40
    }

    ImageButton {
        id: backButton;
        text: qsTr("返回"); rotation: 3
        anchors{right:parent.right; top:parent.top; topMargin: 5; rightMargin: 5}
        scale: 0.8
        onClicked: {
            rollingTimer.stop()
            btnBackClicked();
        }
    }

    Rectangle {
        id: bg
        anchors{
            top: theTitle.bottom;
            topMargin: 10;
            left: parent.left;
            right: parent.right;
            bottom: parent.bottom;
            bottomMargin: 10
            leftMargin: 10
            rightMargin: 10
        }

        width: parent.width
        height: parent.height

        radius: 5
        color:"#9FFFFFFF"

        Text {
            id:title
            font.pointSize: 24
            font.bold: true
            color:"steelblue"
            horizontalAlignment:Text.AlignHCenter
            anchors {
                horizontalCenter: parent.horizontalCenter
                top:parent.top
                topMargin: 5
            }
        }

        Text {
            id:subTitle
            font.pointSize: 16
            font.bold: true
            color:"steelblue"
            horizontalAlignment:Text.AlignHCenter
            anchors {
                horizontalCenter: parent.horizontalCenter
                top:title.bottom
                topMargin: 5
            }
        }

        GridView {
            id:playerView
            anchors{
                top: subTitle.bottom;
                //left: parent.left;
                //right: parent.right;
                bottom: parent.bottom;
                topMargin: 10;
                bottomMargin: 60
                //leftMargin: 20
                //rightMargin: 20
                horizontalCenter: parent.horizontalCenter
            }

            implicitWidth: parent.width
            model:rollingModel
            cellWidth:144
            cellHeight:144
            clip: true
            delegate: Rectangle{
                height: playerView.cellWidth
                width: playerView.cellHeight
                color: "transparent"
                Column {
                    anchors.horizontalCenter: parent.horizontalCenter
                    Image {
                        source: avatarUrl
                        width: 100
                        height: 100
                        fillMode: Image.PreserveAspectFit
                        anchors.horizontalCenter: parent.horizontalCenter
                    }
                    Text {
                        text: name;
                        anchors.horizontalCenter: parent.horizontalCenter
                    }
                    Text {
                        text: depart;
                        anchors.horizontalCenter: parent.horizontalCenter
                    }
                }
                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                    }
                }

            }
        }

        ImageButton {
            id: btnStart;
            text: qsTr("摇奖");
            rotation: 3;
            anchors {
                horizontalCenter: parent.horizontalCenter
                bottom: parent.bottom
                bottomMargin: 5
            }

            onClicked: {
                btnRollingClicked();
            }
        }
    }

    Timer {
        id: rollingTimer
        interval: 80; running: false; repeat: true

        onTriggered: {
            timerFired();
        }
    }

    ListModel {
        id: rollingModel
    }

    Audio {
        id: rollingSound
        source: "musics/musicOfRolling.mp3"
        volume: 0.7
        onStopped:  {
            if(rollingTimer.running) {
                rollingSound.play();
            }
        }
    }

    Audio {
        id: drawSound
        source: "musics/musicOfDraw.mp3"
        volume: 1.0
    }

    Image {
        id:stubImage
        source:"images/attendee_default.png"
        visible: false
    }

    onStageChanged: {
        initStage()
    }

    function initStage() {
        if(stage) {
            console.log("using Stage: prize.count=", stage.prize.count, ", winners.length=",stage.winners.length)

            title.text = stage.prize.title + " " + stage.prize.subTitle
            btnStart.visible = !stage.isCompleted();
            updateWinners();
        }
        else {
            title.text = nil
            subTitle.text = nil
            //players_ = []
            btnStart.visible = false;
        }

        if(rollingModel.count > 0) {
            rollingModel.remove(0, rollingModel.count)
        }
        players_ = [];
        rollingPlayers_ = [];
        groupWinnerCount_ = 0;

        var initGroupCount = stage.nextGroupWinnerCount();
        if(rollingModel.count > 0)
            rollingModel.remove(0, rollingModel.count)
        for(var i=0; i<initGroupCount; ++i) {
            rollingModel.append({name:"?", depart:"", avatarUrl:Qt.resolvedUrl(stubImage.source)})
        }

        var maxCellInRow =  (initGroupCount < 5 ? initGroupCount : 5)
        playerView.width = playerView.cellWidth * maxCellInRow;
    }

    function btnRollingClicked() {
        if(!rollingTimer.running) {
            backButton.visible = false
            drawBegin();

            btnStart.text = qsTr("停止")
            rollingSound.play()

            rolling = true
            rollingTimer.running = true
        }
        else {
            backButton.visible = true
            rollingTimer.running = false
            rolling = false

            drawSound.play();
            rollingSound.stop()
            drawFinish();
        }
    }

    function timerFired() {
        //console.debug("------timerFired")
        var avalidPlayers = []

        var tried = 0
        var playersLength = players_.length

        while ((tried < playersLength) && (avalidPlayers.length < groupWinnerCount_)) {
            ++tried;
            var playerIndex = (++rollingIndex_) % players_.length;
            if(playerIndex < players_.length) {
                var p  = players_[playerIndex]
                if (p) {
                    avalidPlayers.push(p)
                }
            }

        }

        //console.debug("[1]------timerFired")

        if(avalidPlayers.length != groupWinnerCount_) {
            console.error("No Players Avalid. avalidPlayers.length=", avalidPlayers.length, ", groupWinnerCount_=", groupWinnerCount_)
        }

        //console.debug("[2]------timerFired")
        rollingPlayers_ = avalidPlayers

        if(rollingModel.count > 0)
            rollingModel.remove(0, rollingModel.count)

        if(!rollingTimer.running) {
            //console.debug("[8]------timerFired")
        }

        //console.debug("[3]------timerFired")
        for(var k in rollingPlayers_) {
            var pp = rollingPlayers_[k]
            if(pp) {
                //console.debug("[9]------timerFired:", typeof pp)
                rollingModel.append({
                                        name:""+pp.name,
                                        depart:""+pp.depart,
                                        avatarUrl:Qt.resolvedUrl(pp.avatarUrl)
                                    });
            }
            else {
               //console.debug("[7]------timerFired:", typeof pp)
            }
        }
        //console.debug("++++++timerFired")
    }

    function getAvalidPlayers() {
        var aPlayers = []
        for(var i in playerModel) {
            var p = playerModel[i]
            if(p && p.winStatus === 0) {
                aPlayers.push(p)
            }
        }

        //aPlayers.sort(function(){return ((Math.random()>=0.5)?-1:1);});
        return aPlayers;
    }

    function drawBegin() {
        players_ = getAvalidPlayers();
        rollingIndex_ = 0;
        groupWinnerCount_ = stage.nextGroupWinnerCount();
        var maxCellInRow =  (groupWinnerCount_ < 5 ? groupWinnerCount_ : 5)
        playerView.width = playerView.cellWidth * maxCellInRow;

        if(rollingModel.count > 0)
            rollingModel.remove(0, rollingModel.count)
        for(var i=0; i<groupWinnerCount_; ++i) {
            rollingModel.append({name:"?", depart:"", avatarUrl:Qt.resolvedUrl(stubImage.source)})
        }
    }

    function drawFinish() {
        for(var i in rollingPlayers_) {
            var player = rollingPlayers_[i]
            if(player) {
                stage.win(player)
            }
        }

        updateWinners()

        players_ = []
        rollingIndex_ = 0;
        groupWinnerCount_ = 0;

        if(stage.isCompleted()) {
            drawCompleted()
        }
    }

    function drawCompleted() {
        btnStart.visible = false
    }

    function updateWinners() {
        subTitle.text = "剩余" + (stage.prize.count-stage.winners.length)+"名"
    }
}
